import { defineStore } from "pinia";
import { store } from "@/stores";
import type { LoginResult } from "@/api/user";
import type { userType, loginParamsType } from "../types";
import { routerArrays } from "@/layout/types";
import { router, resetRouter } from "@/router";
import { storageSession } from "@pureadmin/utils";
import { loginApi, refreshTokenApi, loginSsoApi } from "@/api/user";
// import { UserResult, RefreshTokenResult } from "@/api/user";
import { useMultiTagsStoreHook } from "@/stores/modules/multiTags";
import { type DataInfo, setToken, removeToken, sessionKey } from "@/utils/auth";

export const useUserStore = defineStore({
  id: "tc-user",
  state: (): userType => ({
    // 用户名
    username:
      storageSession().getItem<DataInfo<number>>(sessionKey)?.username ?? "",
    // 角色权限
    roles: storageSession().getItem<DataInfo<number>>(sessionKey)?.roles,
    // 前端生成的验证码（按实际需求替换）
    verifyCode: "",
    // 判断登录页面显示哪个组件（0：登录（默认）、1：手机登录、2：二维码登录、3：注册、4：忘记密码）
    currentPage: 0,
  }),
  actions: {
    /** 存储用户名 */
    SET_USERNAME(username: string) {
      this.username = username;
    },
    /** 存储角色 */
    SET_ROLES(roles: Array<string>) {
      this.roles = roles;
    },
    /** 存储前端生成的验证码 */
    SET_VERIFYCODE(verifyCode: string) {
      this.verifyCode = verifyCode;
    },
    /** 存储登录页面显示哪个组件 */
    SET_CURRENTPAGE(value: number) {
      this.currentPage = value;
    },
    /** 登入 */
    async loginByUsername(params: loginParamsType) {
      return new Promise<any>((resolve, reject) => {
        // const { username, password, code, tenantId } = params;
        // loginApi(username, password, code, tenantId)
        const { username, password, tenantId } = params;
        loginApi(username, password, tenantId)
          .then((res) => {
            if (res) {
              setToken(res);
              resolve(res);
            }
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    /** sso登入 */
    async loginSsoByUsername() {
      return new Promise<any>((resolve, reject) => {
        // const { username, password, tenantId } = params;
        loginSsoApi()
          .then((res) => {
            if (res) {
              setToken(res);
              resolve(res);
            }
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    /** 前端登出（不调用接口） */
    logOut() {
      this.username = "";
      this.roles = [];
      removeToken();
      useMultiTagsStoreHook().handleTags("equal", [...routerArrays]);
      resetRouter();
      // router.push("/login");
      location.href = "/kg-web/sso/logout";
    },
    /** 刷新`token` */
    async handRefreshToken(data: string) {
      return new Promise<LoginResult<number>>((resolve, reject) => {
        // TODO: 传 储存的 tenantID
        refreshTokenApi(data)
          .then((res) => {
            if (res) {
              setToken(res);
              resolve(res);
            }
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
  },
});

export function useUserStoreHook() {
  return useUserStore(store);
}
